#include "DataTypes.h"

#ifndef SIMPLEMESSAGING_H_
#define SIMPLEMESSAGING_H_


#define MAX_MESSAGE_SIZE 		        (64+2+4)

#define MESSAGE_HEADER_1 	    	  	0xAA
#define MESSAGE_HEADER_2 		      	0xAA
#define MAX_MESSAGE_STRING_LENGTH 	32

#define MESSAGE_FRAMING_SIZE		(2 + 2 + 2)


//State Machine Macros
#define SCAN_FOR_HEADER1                0x00
#define SCAN_FOR_HEADER2                0x01
#define GRAB_LENGTH_LOW                 0x02
#define GRAB_LENGTH_HIGH                0x03
#define GRAB_PAYLOAD                    0x04
#define GRAB_CRC_LOW                    0x05
#define GRAB_CRC_HIGH                   0x06

//Return MACROS
#define NO_MESSAGE_DETECTED              0x00
#define MESSAGE_DETECTED                 0x01
#define BAD_CRC						               0x02
#define INVALID_MSG_LENGTH			         0x03

//MACROS for the commands.  All responses will use same number as the command

//Globals --- Used by all products with this Messaging architecture
#define MSG_UNKNOWN_MESSAGE     	    	  0x01
#define MSG_GET_FIRMWARE_VERSION 		      0x02
#define MSG_SOFTWARE_RESET      		      0x03
#define MSG_BAD_CRC            			      0x04
#define MSG_INVALID_LENGTH     			      0x05
#define MSG_STRING						            0x06
#define MSG_CHANGE_SYSTEM_STATE           0x07
#define MSG_REPORT_FIRMWARE_VERSION		    0x08

//System Specific

#define MSG_POST_SYSTEM_STATE   	 	 	   	 0x10
#define MSG_SET_STEERING_SERVO             0x11
#define MSG_SET_DRIVE_SERVO                0x12
#define MSG_POST_SENSOR_DATA               0x13
#define MSG_SET_AUTO_NV_PARAMETERS         0x14
#define MSG_SIMULATE_BUTTON_PRESS          0x15

#define MSG_POST_AUTO_NV_STATE_VARIABLES   0x16

#define MESSAGE_ID_SIZE						1

typedef union {
		
		struct
		{	BYTE FirmwareVersionMinor;
			BYTE FirmwareVersionMajor;
		}FirmwareVersion;

		struct
		{
			BYTE Current;
		}SystemState;
		
} AncillaryMsgData;


      
extern AncillaryMsgData MyAncillaryMsgData;

BOOL AssembleMessage(BYTE *MsgBuf,BYTE MsgType,WORD *TotalMsgLength, void *AncillaryData);

extern BYTE OutgoingMsgBuf[MAX_MESSAGE_SIZE+MESSAGE_FRAMING_SIZE];
extern WORD OutgoingMsgLength;



typedef struct {

		 BYTE  Header1;
		 BYTE  Header2;
     WORD Length;
		 BYTE  Payload[MAX_MESSAGE_SIZE];
		 WORD CRC;
       	 BYTE DetectState;
       	 WORD DataCnt;
       	 
       } IncomingMsg;


typedef struct
  {
     WORD SteeringServoNeutral;
     SIGNED_WORD SteeringServoVal;
  }  SteeringServoCtrl;
  
  typedef struct
  {
     WORD DriveServoNeutral;
     SIGNED_WORD DriveServoVal;
  }  DriveServoCtrl;


void ProcessIncomingBackdoorMessages(void);
void InitMessageDetect(void);
 BYTE MessageDetect(IncomingMsg * IncomingMessage, BYTE DataIn);
#endif /*SIMPLEMESSAGING_H_*/
